package com.zhugang.week05;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @program algorithms
 * @description: intersection
 * @author: chanzhugang
 * @create: 2022/07/11 11:17
 */
public class Intersection {

    public static void main(String[] args) {
        Intersection intersection = new Intersection();
        int[] num1 = new int[]{4, 9, 5};
        int[] num2 = new int[]{9, 4, 9, 8, 4};
        int[] res = intersection.intersection(num1, num2);
        for (int num : res) {
            System.out.println(num);
        }

    }

    /**
     * 349 两个数组的交集
     *
     * @param nums1
     * @param nums2
     * @return
     */
    public int[] intersection(int[] nums1, int[] nums2) {
        // 哈希表存储其中一个数组元素，遍历另一个数组，判断哈希表是否存在其元素
        Set<Integer> set = new HashSet<>();
        for (int num : nums1) {
            set.add(num);
        }

        List<Integer> list = new ArrayList<>();
        for (int num : nums2) {
            if (set.contains(num)) {
                set.remove(num);
                list.add(num);
            }
        }
        // list to array
        int[] res = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            res[i] = list.get(i);
        }
        return res;
    }
}